//
//  PillowCommandTool.m
//  Lightthings
//
//  Created by 王岩 on 2025/1/10.
//

#import "PillowCommandTool.h"
#import "HABleTool.h"
#include "aes.h"
@implementation PillowCommandTool
SingletonM;


// MARK:   🔥🔥🔥🔥🔥🔥🔥 基础算法 🔥🔥🔥🔥🔥🔥🔥
- (void)writeStormCommand:(PillowCommandEnum)type ToPeripheral:(CBPeripheral *)peripheral Value:(NSArray *)value reBack:(void (^)(NSString * _Nonnull))bacdata {
    Byte HeadData[2] = {0xfe,0xef};// 报文头
    Byte fountionCode[1]  = {0x00}; // 报文类型
    Byte dataLength[1] = {0x00};//报文长度
    Byte check[2] = {0x00,0x00};//  校验
    
    fountionCode[0] = [[self getFoutionCode:type].firstObject intValue] & 0xff;
    
    if (value.count > 0) {
        dataLength[0] = (value.count & 0xff);//低8位
    }
    NSUInteger length = value.count + 2;
    uint8_t crcdata[length];
    crcdata[0] = [[self getFoutionCode:type].firstObject intValue];
    crcdata[1] = value.count;
    for (int i = 0; i < value.count; i ++) {
        crcdata[i + 2] = [value[i] intValue];
    }
    uint16_t a = calcCrc16(crcdata, sizeof(crcdata));
//    NSLog(@"%04x",a);
    
    NSMutableData * allCommand = [[NSMutableData alloc] initWithBytes:HeadData length:sizeof(HeadData)];
    [allCommand appendBytes:fountionCode length:sizeof(fountionCode)];
    [allCommand appendBytes:dataLength length:sizeof(dataLength)];
    
    for (int i = 0; i < value.count; i ++) {
        Byte b = [value[i] intValue] & 0xff;
        Byte byte[] = {b};
        [allCommand appendBytes:byte length:sizeof(byte)];
    }
    
    check[1] = a & 0xff;
    check[0] = (a & 0xff00)>>8;
    
    [allCommand appendBytes:check length:sizeof(check)];

    DDLogDebug(@"发送枕头数据 allCommand  = %@", allCommand);

    [[FRQBluetoothManager shareManager] sendPillowCommandData:allCommand ToPeripheral:peripheral completion:^(NSString * _Nonnull resultString) {
        if (resultString.length < 6) {
            return;
        }
        NSString * code = [resultString substringWithRange:NSMakeRange(4, 2)];
        DDLogDebug(@"返回枕头数据：%@， 指令：%@",resultString, code);
//        if ([[resultString substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"b3"]) {
//            return;
//        }
//        NSString * a = [resultString substringWithRange:NSMakeRange(18, 2)];
//        NSString * b = [resultString substringWithRange:NSMakeRange(20, 2)];
//        
//        if (strtoll([[NSString stringWithFormat:@"0x%@",a] UTF8String], 0, 16) == [[self getFoutionCode:type].firstObject intValue] && strtoll([[NSString stringWithFormat:@"0x%@",b] UTF8String], 0, 16) == [[self getFoutionCode:type].lastObject intValue]) {
            bacdata(resultString);
//        }else {
//            bacdata(nil);
//        }
        
    }];
}

- (NSArray *)getFoutionCode:(PillowCommandEnum)type {
    switch (type) {
        case Pillow_UpdateDate:
            return @[@(0x40)];
            break;
        case Pillow_ReadDate:
            return @[@(0x41)];
            break;
        case Pillow_StartMassage:
            return @[@(0xb3)];
            break;
        case Pillow_Synchronous:
            return @[@(0x21)];
            break;
        case Pillow_RespondSynchronous:
            return @[@(0x22)];
            break;
        case Pillow_SnoreInterventionIntensity:
            return @[@(0x38)];
            break;
        case Pillow_RelaxSet:
            return @[@(0x34)];
            break;
        case Pillow_GetMassage:
            return @[@(0x35)];
            break;
        case Pillow_GradeSnoring:
            return @[@(0x39)];
            break;
        default:
            break;
    }
    return @[@0,@0];
}

- (void)updateDateAndTimeCallBack:(void (^)(NSString * data))backBlock RealTimeData:(BOOL)open1 StopSwith:(BOOL)open2 ToPeripheral:(CBPeripheral *)peripheral{
    
    NSMutableArray * dataArray = [NSMutableArray array];
    /// 时间戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
     [formatter setDateStyle:NSDateFormatterMediumStyle];
     [formatter setTimeStyle:NSDateFormatterShortStyle];
     [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
     //设置时区,这个对于时间的处理有时很重要
     NSTimeZone* timeZone = [NSTimeZone systemTimeZone];
     [formatter setTimeZone:timeZone];
     NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    long value = (long)[datenow timeIntervalSince1970];
    unsigned char byte1 = (value & 0xff000000)>>24;
    unsigned char byte2 = (value & 0xff0000)>>16;
    unsigned char byte3 = (value & 0xff00)>>8;
    unsigned char byte4 = (value & 0xff);
    
    unsigned char byte5 = (open1 & 0xff);
    unsigned char byte6 = (open2 & 0xff);
    
    [dataArray addObject:@(byte1)];
    [dataArray addObject:@(byte2)];
    [dataArray addObject:@(byte3)];
    [dataArray addObject:@(byte4)];
    [dataArray addObject:@(byte5)];
    [dataArray addObject:@(byte6)];
//    dataArray = @[@(0x00),@(0x00),@(0xEF),@(0x10),@(0x00),@(0),@(0xFD),@(0x20)];
    [[PillowCommandTool sharedInstance] writeStormCommand:Pillow_UpdateDate ToPeripheral:peripheral Value:dataArray reBack:^(NSString * _Nonnull backData) {
        
        if ([[backData substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"c0"]) {
            backBlock(backData);
        }else {
            backBlock(backData);
        }
    }];
    
}

- (void)SynchronousDataCallBack:(void (^)(NSString * data))backBlock  ToPeripheral:(CBPeripheral *)peripheral {
    
    NSString * last = [[NSUserDefaults standardUserDefaults] valueForKey:@"lastSyschronousDate"];
    if (!last) {
       last = [MBDateManager shortStringFromDate:[NSDate dateWithTimeIntervalSince1970:0]];
        
    }
    last = @"1736476205";
    
    NSString * dateStr = [NSString stringWithFormat:@"%@ 00:00", [MBDateManager dateTransformString:[NSDate date] style:@"yyyy-MM-dd"]];
    last = [MBDateManager shortStringFromDate:[MBDateManager stringTransformDate:dateStr style:@"yyyy-MM-dd HH:mm"]];
    
    long value = [last longValue] / 1000;
    NSMutableArray * dataArray = [NSMutableArray array];

    unsigned char byte1 = (value & 0xff000000)>>24;
    unsigned char byte2 = (value & 0xff0000)>>16;
    unsigned char byte3 = (value & 0xff00)>>8;
    unsigned char byte4 = (value & 0xff);
    
    [dataArray addObject:@(byte1)];
    [dataArray addObject:@(byte2)];
    [dataArray addObject:@(byte3)];
    [dataArray addObject:@(byte4)];
    
    [self writeStormCommand:Pillow_Synchronous ToPeripheral:peripheral Value:dataArray reBack:^(NSString * _Nonnull data) {
        backBlock(data);
    }];
    
}

- (void)SynchronousDataRespondValue:(NSArray *)value CallBack:(void (^)(NSString * data))backBlock  ToPeripheral:(CBPeripheral *)peripheral {
    [self writeStormCommand:Pillow_RespondSynchronous ToPeripheral:peripheral Value:value reBack:^(NSString * _Nonnull data) {
        if ([[data substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"a2"]) {
//            NSMutableArray * dataArray = [NSMutableArray array];
//            NSString * sort = [data substringWithRange:NSMakeRange(8, 4)];
//            long a = strtoll([[NSString stringWithFormat:@"0x%@",sort] UTF8String], 0, 16);
//            [dataArray removeAllObjects];
//            unsigned char byte3 = (a & 0xff00)>>8;
//            unsigned char byte4 = (a & 0xff);
//            [dataArray addObject:@(byte3)];
//            [dataArray addObject:@(byte4)];
//            [dataArray addObject:@(1)];
//            [self SynchronousDataRespondValue:dataArray CallBack:backBlock ToPeripheral:peripheral];
        }else if ([[data substringWithRange:NSMakeRange(4, 2)] isEqualToString:@"a3"]){
            
        }
        backBlock(data);
    }];
}

- (void)analyzeSynchronousData:(NSString *)data {
    
}

@end
